<?php
/**
 * Created by PhpStorm.
 * Author: MeiJay
 * Date: 2020/2/24
 * Time: 23:03
 */

namespace App\Admin\Controllers;

use App\Admin\Forms\PurchaseOrder\Import;
use App\Admin\Services\PurchaseService;
use App\Http\Controllers\Controller;
use App\Model\PurchaseOrder;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class PurchaseOrderController extends Controller
{

    public function index(Content $content)
    {
        $grid = new Grid(new PurchaseOrder());
        $grid->setTitle("订货单列表");
        $grid->model()->orderBy('id', 'desc');

        // 如果是供货商
        if (Admin::user()->isRole('supplier')) {
            $grid->model()->where('supplier_id', Admin::user()->id);
        }


        $grid->column('id', '序号');
        $grid->column('operator.username', '操作人');
        $grid->column('supplier.username', '供应商');

        $grid->column('created_at', '创建时间');

        $grid->column('noHandleCount.count', '是否导出')->display(function ($count, $column) {

            if ($count) {

                return "<span class='label label-info'>正在处理中</span>";
            }

            return "<a href='export?id={$this->id}' target='_blank'><i class='fa fa-download'></i>点击导出</a>";

        });

        $grid->disableCreateButton();
        $grid->disableExport();
        $grid->disableFilter();


        $grid->actions(function ($actions) {
            // 去掉编辑
            $actions->disableEdit();
            // 去掉查看
            $actions->disableView();
        });

        $grid->paginate(10);

        return $content->row($grid);
    }


    /**
     * @desc 订货单导入
     *
     * @param Content $content
     *
     * @return Content
     *
     * @author: 梅杰[meijie3169@dingtalk.com] at 2020-03-10 12:07:42
     */
    public function import(Content $content)
    {
        // 选填
        $content->header('订货单导入');

        // 选填
        $content->description('订货单导入');

        return $content->body(new Import());
    }


    /**
     * 导出
     *
     * @param Request $request
     * @param PurchaseService $purchaseService
     * @return RedirectResponse
     *
     * @author: 梅杰 2020/3/15 13:44
     */
    public function export(Request $request, PurchaseService $purchaseService)
    {
        if ($id = $request->input('id')) {
            return $purchaseService->export($id);
        }

        return back();
    }
}
